package com.mogist.hqc.module.main.ui

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import com.baidu.location.BDLocation
import com.baidu.location.BDLocationListener
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.event.SearchEvent
import com.mogist.hqc.entitys.response.*
import com.mogist.hqc.module.community.ui.CommunityDetailActivity
import com.mogist.hqc.module.community.ui.CommunityListActivity
import com.mogist.hqc.module.main.adapter.CardFragmentPagerAdapter
import com.mogist.hqc.module.main.adapter.MainAdapter
import com.mogist.hqc.module.main.adapter.ShadowTransformer
import com.mogist.hqc.module.main.adapter.TypeAdapter
import com.mogist.hqc.module.main.contract.MainContract
import com.mogist.hqc.module.main.presenter.MainPresenter
import com.mogist.hqc.module.personal.ui.PersonalActivity
import com.mogist.hqc.module.product.ui.ProductDetailActivity
import com.mogist.hqc.module.product.ui.ProductListActivity
import com.mogist.hqc.module.route.ui.RouteMainActivity
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.DistanceUtil
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.ScrollLayout
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.collections.forEachWithIndex
import org.jetbrains.anko.contentView
import talex.zsw.basecore.interfaces.OnSimpleListener
import talex.zsw.basecore.util.*
import talex.zsw.basecore.util.glide.GlideApp
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.popupwindow.PopLayout
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.SampleHeader
import java.util.*

/**
 * 作用：首页
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class MainActivity : BaseMVPActivity<MainContract.Presenter>(), MainContract.View
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if (!this.isTaskRoot)
        {
            val intent = intent
            if (intent != null)
            {
                val action = intent.action
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action)
                {
                    finish()
                    return
                }
            }
        }
        super.onCreate(savedInstanceState)
    }

    override fun initArgs(intent: Intent?)
    {
    }

    override fun initView()
    {
        setContentView(R.layout.activity_main)
        mPresenter = MainPresenter(this)
    }

    override fun initData()
    {
        initScrollLayout()
        initRecyclerView()
        initViewPageListener()
        initMap()
        // 接口
        mainRoute()
    }

    @Optional
    @OnClick(R.id.mTvLine,
             R.id.mTvSearch,
             R.id.mIvSearchClear,
             R.id.mIvPersonal,
             R.id.mTvProduct,
             R.id.mTvCommunity,
             R.id.mTvDestination,
             R.id.mLLFoot,
             R.id.mIvSelect,
             R.id.mTvToTop,
             R.id.mIvMore)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mIvPersonal    ->
                { // 个人中心
                    if (isLogin())
                    {
                        start(PersonalActivity::class.java)
                    }
                }
                R.id.mTvSearch      ->
                { // 首页搜索
                    if (mRvType.visibility == View.GONE)
                    {
                        mainType()
                    }
                    else
                    {
                        val intent = Intent(this@MainActivity, SearchActivity::class.java)
                        if (mIvMore.visibility == View.VISIBLE)
                        {
                            intent.putExtra("type", selectType)
                        }
                        intent.putExtra("keyword", keyword)
                        start(intent)
                    }
                }
                R.id.mIvSearchClear ->
                {
                    cleanSearch()
                }
                R.id.mTvLine        ->
                { // 行程线路
                    start(RouteMainActivity::class.java)
                }
                R.id.mTvProduct     ->
                { // 玩家产品
                    start(ProductListActivity::class.java)
                }
                R.id.mTvCommunity   ->
                { // 微社区
                    start(CommunityListActivity::class.java)
                }
                R.id.mTvDestination ->
                { // 目的地
                    mScrollLayout.setToOpen()
                    mLLFoot.visibility = View.VISIBLE
                    mLLTop.visibility = View.GONE
                    mTvToTop.visibility = View.GONE
                    mRecyclerView.scrollToPosition(0)
                    if (fragmentDatas.isEmpty())
                    {
                        mainTypeList()
                    }
                }
                R.id.mLLFoot        ->
                {
                    mScrollLayout.setToClosed()
                    mLLFoot.visibility = View.GONE
                    mLLTop.visibility = View.VISIBLE
                }
                R.id.mIvMore        ->
                { // 首页更多
                    showPop()
                }
                R.id.mTvToTop       ->
                { // 到达顶部
                    mTvToTop.visibility = View.GONE
                    mRecyclerView.scrollToPosition(0)
                }
                R.id.mIvSelect      ->
                { // 跳转到当前定位
                    //                    if (selectType == "ROUTE")
                    //                    {
                    //                        mIvSelect.visibility = View.VISIBLE
                    //                    }
                    //                    else
                    //                    {
                    //                        mIvSelect.visibility = View.GONE
                    //                    }
                    mCurrentLat = MathTool.round(SpTool.getString(Constant.STR_LATITUDE), 4)
                    mCurrentLon = MathTool.round(SpTool.getString(Constant.STR_LONGITUDE), 4)
                    curLatLng = LatLng(mCurrentLat, mCurrentLon)
                    cleanSearch()
                }
            }
        }
    }

    override fun onBackPressed()
    {
        exit()
    }

    private fun exit()
    {
        if (closeApp)
        {
            mHandler.removeMessages(0)
            mApplication.exit()
            finish()
        }
        else
        {
            RxToast.normal("再次返回后关闭程序")
            closeApp = true
            mHandler.sendEmptyMessageDelayed(0, 2500)
        }
    }

    private var closeApp = false
    private val mHandler = object : Handler()
    {
        override fun handleMessage(msg: Message?)
        {
            super.handleMessage(msg)
            closeApp = false
        }
    }
    // ============================== 接口数据 start ==============================
    private var hasError = false

    override fun mainListError(type: Int)
    {
        hasError = true
        if (type == 0)
        {
            mainCommunity()
        }
        else if (type == 1)
        {
            mainProduct()
        }
        else if (type == 2)
        {
            if (adapter.data.size == 0)
            {
                showDialog(SweetAlertDialog.ERROR_TYPE,
                           "首页数据获取失败",
                           "是否立即重试？",
                           "重试",
                           "取消",
                           SweetAlertDialog.OnSweetClickListener {
                               mainRoute()
                           },
                           null)
            }
            else
            {
                disDialog()
            }
            mainType()
        }
    }

    /** 首页线路推荐 **/
    override fun mainRoute()
    {
        adapter.replaceData(arrayListOf())
        hasError = false
        val body = BaseModel(true)
        mPresenter.getData(HttpDto(Constant.MAIN_ROUTE, body).setType(HttpDto.GET))
    }

    override fun bindRoute(data: MainRouteListVo)
    {
        if (data.list != null && data.list.isNotEmpty())
        {
            var sum = 5
            if (data.list.size < 5)
            {
                sum = data.list.size
            }
            for (x in 0 until sum)
            {
                adapter.addData(MainVo(data.list[x]))
            }
        }
        mainCommunity()
    }

    /** 首页微社区推荐 **/
    override fun mainCommunity()
    {
        val body = BaseModel(true)
        mPresenter.getData(HttpDto(Constant.MAIN_COMMUNITY, body).setType(HttpDto.GET))
    }

    override fun bindCommunity(data: CommunityListVo)
    {
        if (data.list != null && data.list.isNotEmpty())
        {
            adapter.addData(MainVo(data))
        }
        mainProduct()
    }

    /** 首页产品推荐 **/
    override fun mainProduct()
    {
        val body = BaseModel(true)
        mPresenter.getData(HttpDto(Constant.MAIN_PRODUCT, body).setType(HttpDto.GET))
    }

    override fun bindProduct(data: MainProductListVo)
    {
        disDialog()
        if (data.list != null && data.list.isNotEmpty())
        {
            data.list.forEach {
                adapter.addData(MainVo(it))
            }
        }
        mainType()
    }

    /** 首页项目分类列表 **/
    override fun mainType()
    {
        val body = BaseModel()
        mPresenter.getData(HttpDto(Constant.TYPES, body, true).setType(HttpDto.GET).setTryAgain(true).setErrorTitle("获取产品分类列表失败"))
    }

    override fun bindTypes(list: ArrayList<MainTypeVo>?)
    {
        if (list == null || list.isEmpty())
        {
            selectType = ""
            selectTypeName = ""
        }
        else
        {
            selectType = list[0].type
            selectTypeName = list[0].name
            list[0].isSelect = true
            typeAdapter.setTemp(0)
            initRecyclerViewType(list)
        }
    }

    private fun mainTypeList()
    {
        if (mCurrentLat == 0.0 && mCurrentLon == 0.0)
        {
            if (RegTool.isEmpty(SpTool.getString(Constant.STR_LATITUDE)))
            {
                RxToast.error("请授权地理位置权限,否则无法获取周边信息")
                PermissionHelper.showOpenAppSettingDialog()
                return
            }
            else
            {
                mCurrentLat = MathTool.round(SpTool.getString(Constant.STR_LATITUDE), 4)
                mCurrentLon = MathTool.round(SpTool.getString(Constant.STR_LONGITUDE), 4)
            }
        }
        page = 1
        hasMore = false
        cardSize = 0
        curLatLng = LatLng(mCurrentLat, mCurrentLon)
        val body = BaseModel()
        body.startLat = mCurrentLat.toString()
        body.startLong = mCurrentLon.toString()
        body.type = selectType
        body.distance = Constant.STR_DISTANCE
        body.keyWord = keyword
        body.page = page.toString()
        mPresenter.getData(HttpDto(Constant.TYPE_LIST, body).setType(HttpDto.GET))
    }

    // ============================== 接口数据 end ==============================
    // ============================== 首页数据 start ==============================
    private val adapter = MainAdapter(arrayListOf())

    private fun initRecyclerView()
    {
        adapter.setOnItemChildClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                val vo = adapter.getItem(position) as MainVo
                when (view.id)
                {
                    R.id.layout0 ->
                    { // 线路详情
                        val intent = Intent(this@MainActivity, RouteMainActivity::class.java)
                        intent.putExtra("id", vo.route.id)
                        start(intent)
                    }
                    R.id.i1LL0   ->
                    { // 微社区详情
                        val intent = Intent(this@MainActivity, CommunityDetailActivity::class.java)
                        intent.putExtra("id", vo.community.list[0].id)
                        start(intent)
                    }
                    R.id.i1LL1   ->
                    { // 微社区详情
                        val intent = Intent(this@MainActivity, CommunityDetailActivity::class.java)
                        intent.putExtra("id", vo.community.list[1].id)
                        start(intent)
                    }
                    R.id.i1LL2   ->
                    { // 微社区详情
                        val intent = Intent(this@MainActivity, CommunityDetailActivity::class.java)
                        intent.putExtra("id", vo.community.list[2].id)
                        start(intent)
                    }
                    R.id.iTvGo   ->
                    { // 微社区
                        start(CommunityListActivity::class.java)
                    }
                    R.id.layout2 ->
                    { // 产品详情
                        val intent = Intent(this@MainActivity, ProductDetailActivity::class.java)
                        intent.putExtra("id", vo.product.id)
                        start(intent)
                    }
                }
            }
        }
        adapter.emptyView =
                SampleHeader(this@MainActivity, mRecyclerView.width, mRecyclerView.height)
        adapter.isUseEmpty(false)
        mRecyclerView.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL_LIST,
                                                              R.color.white))
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = adapter
        mRecyclerView.isNestedScrollingEnabled = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            mRecyclerView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                if (layoutManager.findFirstVisibleItemPosition() > 0)
                {
                    mTvToTop.visibility = View.VISIBLE
                }
                else
                {
                    mTvToTop.visibility = View.GONE
                }
            }
        }
        val head = layoutInflater.inflate(R.layout.head_main, null)
        head.setOnClickListener {
            mScrollLayout.setToClosed()
            mLLFoot.visibility = View.GONE
            mLLTop.visibility = View.VISIBLE
        }
        adapter.addHeaderView(head)
    }

    val layoutManager = LinearLayoutManager(this@MainActivity)

    private fun initScrollLayout()
    {
        mScrollLayout.setOnScrollChangedListener(object : ScrollLayout.OnScrollChangedListener
                                                 {
                                                     override fun onScrollProgressChanged(currentProgress: Float)
                                                     {
                                                         // 0 to 1, 1 to -1
                                                         // 0 means close, 1 means open, -1 means exit.
                                                         if (currentProgress > 0 && currentProgress < 1)
                                                         {
                                                             if (mLLTop.visibility == View.GONE)
                                                             {
                                                                 mLLTop.visibility = View.VISIBLE
                                                             }
                                                             if (mLLFoot.visibility == View.GONE)
                                                             {
                                                                 mLLFoot.visibility = View.VISIBLE
                                                             }
                                                         }
                                                         if (currentProgress in 0.0..1.0)
                                                         {
                                                             mLLTop.alpha = 1 - currentProgress
                                                             mRecyclerView.alpha = 1 - currentProgress
                                                             mLLFoot.alpha = currentProgress
                                                         }
                                                     }

                                                     override fun onScrollFinished(currentStatus: ScrollLayout.Status)
                                                     {
                                                         when (currentStatus)
                                                         {
                                                             ScrollLayout.Status.CLOSED                           ->
                                                             {
                                                                 LogTool.nd(" CLOSED ")
                                                                 mLLFoot.visibility = View.GONE
                                                                 mIvMore.visibility = View.GONE
                                                             }
                                                             ScrollLayout.Status.OPENED, ScrollLayout.Status.EXIT ->
                                                             {
                                                                 LogTool.nd(" OPENED ")
                                                                 mLLTop.visibility = View.GONE
                                                                 mTvToTop.visibility = View.GONE
                                                                 mIvMore.visibility = View.VISIBLE
                                                                 if (mRvType.visibility == View.GONE)
                                                                 {
                                                                     mainType()
                                                                 }
                                                                 else if (fragmentDatas.isEmpty() && RegTool.isEmpty(keyword))
                                                                 {
                                                                     mainTypeList()
                                                                 }
                                                             }
                                                         }
                                                     }

                                                     override fun onChildScroll(top: Int)
                                                     {
                                                     }
                                                 })
        Tool.delayToDo(200) {
            try
            {
                val dp105 = DimenTool.dp2px(105f)
                if (contentView!!.height - dp105 > 0)
                {
                    mScrollLayout.setTrueMaxOffset(contentView!!.height - dp105)
                    mScrollLayout.setTrueExitOffset(contentView!!.height - dp105)
                }
            }
            catch (e: Exception)
            {
                e.printStackTrace()
            }
        }
    }

    // ============================== 首页数据 end ==============================
    // ============================== 首页地图数据类型 start ==============================
    private val typeAdapter = TypeAdapter()
    var selectType = ""
    var selectTypeName = ""
    private fun initRecyclerViewType(list: ArrayList<MainTypeVo>)
    {
        mRvType.visibility = View.VISIBLE
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                if (typeAdapter.changeSelect(position))
                {
                    val vo = adapter.getItem(position) as MainTypeVo
                    selectType = vo.type
                    selectTypeName = vo.name
                    mainTypeList()
                }
                else
                {
                }
            }
        }
        typeAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRvType.addItemDecoration(DividerItemDecoration(DividerItemDecoration.HORIZONTAL_LIST,
                                                        R.color.transparent))
        mRvType.layoutManager =
                LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false)
        mRvType.adapter = typeAdapter
        typeAdapter.replaceData(list)
    }

    // ============================== 首页地图数据类型 end ==============================
    // ============================== 地图 start ==============================
    private var mBaiduMap: BaiduMap? = null
    // 是否首次定位
    private var isFirstLoc = true
    // 是否开启定位图层
    private var myLocationData: MyLocationData? = null
    // 定位相关
    private var mLocClient: LocationClient? = null
    private val myListener = MyLocationListener()
    private var mCurrentDirection = 0
    private var mCurrentLat = 0.0
    private var mCurrentLon = 0.0
    private var mCurrentAccracy: Float = 0.toFloat()
    private var curLatLng: LatLng? = null // 选中点的位置
    private var myLocLatLng: LatLng? = null // 定位点位置

    private fun initMap()
    {
        mBaiduMap = mMapView.map
        requestPermission()
        initLocation()
        initListener()
    }

    private var isPermissionRequested: Boolean = false

    /**
     * Android6.0之后需要动态申请权限
     */
    private fun requestPermission()
    {
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested)
        {
            PermissionHelper.check(OnSimpleListener {
                isFirstLoc = true
                isPermissionRequested = true
            }, PermissionConstants.LOCATION, PermissionConstants.STORAGE)
            //            isPermissionRequested = true
            //            val permissionsList = ArrayList<String>()
            //            val permissions =
            //                    arrayOf(Manifest.permission.ACCESS_NETWORK_STATE,
            //                            Manifest.permission.INTERNET,
            //                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            //                            Manifest.permission.READ_EXTERNAL_STORAGE,
            //                            Manifest.permission.ACCESS_COARSE_LOCATION,
            //                            Manifest.permission.ACCESS_FINE_LOCATION,
            //                            Manifest.permission.ACCESS_WIFI_STATE)
            //
            //            for (perm in permissions)
            //            {
            //                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm))
            //                {
            //                    permissionsList.add(perm)
            //                }
            //            }
            //
            //            if (permissionsList.isNotEmpty())
            //            {
            //                val strings = arrayOfNulls<String>(permissionsList.size)
            //                requestPermissions(permissionsList.toTypedArray(), 0)
            //                PermissionHelper.showOpenAppSettingDialog("定位所必须的权限未能获取,请先授权")
            //            }
            //            else
            //            {
            //                isFirstLoc = true
            //            }
        }
    }

    /**
     * 定位初始化
     */
    private fun initLocation()
    {
        // 开启定位图层
        mBaiduMap?.isMyLocationEnabled = true
        // 定位初始化
        mLocClient = LocationClient(this)
        mLocClient?.registerLocationListener(myListener)
        val option = LocationClientOption()
        // 打开gps
        option.isOpenGps = true
        // 设置坐标类型
        option.setCoorType("bd09ll")
        option.setScanSpan(60 * 1000)
        mLocClient?.setLocOption(option)
        mLocClient?.start()
        // 传入null，则为默认图标
        mBaiduMap?.setMyLocationConfiguration(MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                                                                      true,
                                                                      null))
        val builder1 = MapStatus.Builder()
        builder1.overlook(0f)
        mBaiduMap?.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()))
    }

    /**
     * 定位SDK监听函数
     */
    inner class MyLocationListener : BDLocationListener
    {
        override fun onReceiveLocation(location: BDLocation?)
        {
            // MapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
            {
                return
            }
            if (mCurrentLat == 0.0)
            {
                mCurrentLat = location.latitude
                mCurrentLon = location.longitude
            }
            SpTool.saveString(Constant.STR_LATITUDE, location.latitude.toString())
            SpTool.saveString(Constant.STR_LONGITUDE, location.longitude.toString())
            mCurrentAccracy = location.radius
            myLocationData =
                    MyLocationData.Builder()
                            .accuracy(location.radius) // 设置定位数据的精度信息，单位：米
                            .direction(mCurrentDirection.toFloat()) // 此处设置开发者获取到的方向信息，顺时针0-360
                            .latitude(location.latitude)
                            .longitude(location.longitude)
                            .build()
            mBaiduMap?.setMyLocationData(myLocationData)
            myLocLatLng = LatLng(location.latitude, location.longitude)
            if (isFirstLoc)
            {
                isFirstLoc = false
                val ll = LatLng(location.latitude, location.longitude)
                val builder = MapStatus.Builder()
                builder.target(ll)
                        .zoom(18.0f)
                mBaiduMap?.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
            }
        }
    }

    override fun onResume()
    {
        super.onResume()
        // 在activity执行onResume时必须调用mMapView. onResume ()
        mMapView.onResume()
        if (adapter.itemCount == 0 && hasError)
        {
            mainRoute()
        }
        if (!RegTool.isEmpty(SpTool.getString(Constant.STR_USER_PHOTO)))
        {
            GlideApp.with(mIvPersonal.context)
                    .load(SpTool.getString(Constant.STR_USER_PHOTO))
                    .centerCrop()
                    .into(mIvPersonal)
        }
        checkToken()
    }

    override fun onPause()
    {
        super.onPause()
        // 在activity执行onPause时必须调用mMapView. onPause ()
        mMapView.onPause()
    }

    override fun onDestroy()
    {
        super.onDestroy()
        // 退出时销毁定位
        mLocClient?.stop()
        // 关闭定位图层
        mBaiduMap?.isMyLocationEnabled = false
        // 在activity执行onDestroy时必须调用mMapView.onDestroy()
        mMapView.onDestroy()
        markerIcon.recycle()
        markerIconBig.recycle()
        markerList.clear()
    }

    private val markerIconBig = BitmapDescriptorFactory.fromResource(R.drawable.i_mark2)
    private val markerIcon = BitmapDescriptorFactory.fromResource(R.drawable.i_mark)
    private var markerList: ArrayList<Marker> = arrayListOf()
    private var selectMarkerPos = -1

    private fun addMark(data: MainItemVo, pos: Int)
    {
        mBaiduMap?.let {
            //定义Maker坐标点
            val point = LatLng(MathTool.mul(data.latitude, "1"), MathTool.mul(data.longitude, "1"))
            //构建Marker图标
            val bundle = Bundle()
            bundle.putSerializable("data", data)
            bundle.putInt("pos", pos)
            //构建MarkerOption，用于在地图上添加Marker
            val option =
                    MarkerOptions().position(point)
                            .extraInfo(bundle)
            if (pos == 0)
            {
                option.icon(markerIconBig)
                if (selectType != "ROUTE")
                {
                    curLatLng =
                            LatLng(MathTool.mul(data.latitude, "1"),
                                   MathTool.mul(data.longitude, "1"))
                }
            }
            else
            {
                option.icon(markerIcon)
            }
            //在地图上添加Marker，并显示
            markerList.add(mBaiduMap!!.addOverlay(option) as Marker)
        }
    }

    private fun moveTo(data: MainItemVo?)
    {
        if (data != null)
        {
            LogTool.ni("移动镜头到 -> " + data.proName)
            val point = LatLng(MathTool.mul(data.latitude, "1"), MathTool.mul(data.longitude, "1"))
            mBaiduMap?.setMapStatus(MapStatusUpdateFactory.newLatLng(point))
        }
    }

    private fun initListener()
    {
        val listener = object : BaiduMap.OnMapStatusChangeListener
        {
            /** 手势操作地图，设置地图状态等操作导致地图状态开始改变。 */
            override fun onMapStatusChangeStart(p0: MapStatus?)
            {
            }

            /** 手势操作地图，设置地图状态等操作导致地图状态开始改变。 */
            //用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
            //int REASON_GESTURE = 1;
            //SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
            //int REASON_API_ANIMATION = 2;
            //开发者调用,导致的地图状态改变
            //int REASON_DEVELOPER_ANIMATION = 3;
            override fun onMapStatusChangeStart(p0: MapStatus, p1: Int)
            {
            }

            /** 地图状态变化中 */
            override fun onMapStatusChange(p0: MapStatus?)
            {
            }

            /** 地图状态改变结束 */
            override fun onMapStatusChangeFinish(p0: MapStatus)
            {
                // 判断距离上一个选中的景点的距离超过了 20km 且不是线路 就加载新数据
                curLatLng?.let {
                    if (DistanceUtil.getDistance(p0.target, curLatLng) > Constant.DOUBLE_DISTANCE)
                    {
                        if (selectType != "ROUTE")
                        {
                            curLatLng = p0.target
                            mCurrentLat = p0.target.latitude
                            mCurrentLon = p0.target.longitude
                            mainTypeList()
                        }
                    }
                }
                // 判断超过自己定位 20km 则显示回到自己位置的图标
                //                myLocLatLng?.let {
                //                    if (DistanceUtil.getDistance(p0.target, myLocLatLng) > Constant.DOUBLE_DISTANCE)
                //                    {
                //                        mIvSelect.visibility = View.VISIBLE
                //                    }
                //                    else
                //                    {
                //                        mIvSelect.visibility = View.GONE
                //                    }
                //                }
                // 线路则一直显示自己的定位图标
                //                if (selectType == "ROUTE")
                //                {
                //                    mIvSelect.visibility = View.VISIBLE
                //                }
            }
        }
        mBaiduMap?.setOnMapStatusChangeListener(listener)
        mBaiduMap?.setOnMarkerClickListener { marker ->
            marker.icon = markerIconBig
            if (selectType != "ROUTE")
            {
                curLatLng = marker.position
            }
            val bundle = marker.extraInfo
            val pos = bundle.getInt("pos")
            val data: MainItemVo = bundle.getSerializable("data") as MainItemVo
            LogTool.ni("点击 -> " + data.proName)
            if (selectMarkerPos >= 0 && selectMarkerPos != pos)
            {
                try
                {
                    markerList[selectMarkerPos].icon = markerIcon
                    selectMarkerPos = pos
                    mViewPager.currentItem = pos
                    moveTo(data)
                }
                catch (e: Exception)
                {
                    e.printStackTrace()
                }
            }
            true
        }
    }

    // ============================== 地图 end ==============================
    // ============================== 目的地卡片 start ==============================
    private var mFragmentCardAdapter: CardFragmentPagerAdapter? = null
    private var mFragmentCardShadowTransformer: ShadowTransformer? = null
    private var fragmentDatas: ArrayList<MainItemVo> = arrayListOf()
    private var page = 1
    private var hasMore = false
    private var cardSize = 0
    override fun initCard(data: MainTypeItemVo?, msg: String?)
    {
        disDialog()
        if (!hasMore)
        {
            markerList = arrayListOf()
            mBaiduMap?.clear()
            selectMarkerPos = -1
            mFragmentCardAdapter?.clean()
            mViewPager.removeAllViews()
        }
        if (data == null || data.list.isEmpty())
        {
            hasMore = false
            mViewPager.visibility = View.GONE
            mTvError.visibility = View.VISIBLE
            if (RegTool.isEmpty(msg))
            {
                if (RegTool.isNotEmpty(keyword))
                {
                    mTvError.text = "未能搜索到 <${keyword}> 相关的 $selectTypeName 产品数据"
                }
                else
                {
                    mTvError.text = "您附近没有 $selectTypeName 产品数据"
                }
            }
            else
            {
                mTvError.text = msg
            }
        }
        else
        {
            if (hasMore)
            {
                if (data.pages == page)
                {
                    hasMore = false
                }
                else
                {
                    hasMore = true
                    page++
                }
                cardSize += data.list.size
                data.list.forEachWithIndex { i, mainItemVo ->
                    addMark(mainItemVo, i)
                    val fragment = CardFragment()
                    val bundle = Bundle()
                    bundle.putInt("pos", i)
                    fragment.arguments = bundle
                    mFragmentCardAdapter?.addCardFragment(fragment)
                }
                fragmentDatas.addAll(data.list)
                mFragmentCardAdapter?.notifyDataSetChanged()
            }
            else
            {
                if (data.pages == page)
                {
                    hasMore = false
                }
                else
                {
                    hasMore = true
                    page++
                }
                cardSize += data.list.size
                data.list.forEachWithIndex { i, mainItemVo ->
                    addMark(mainItemVo, i)
                }
                mViewPager.visibility = View.VISIBLE
                mTvError.visibility = View.GONE
                mViewPager.currentItem = 0
                fragmentDatas = data.list
                mFragmentCardAdapter =
                        CardFragmentPagerAdapter(supportFragmentManager,
                                                 DimenTool.dp2px(2F).toFloat(),
                                                 fragmentDatas)
                mFragmentCardShadowTransformer = ShadowTransformer(mViewPager, mFragmentCardAdapter)
                mFragmentCardShadowTransformer?.enableScaling(true)

                mViewPager.adapter = mFragmentCardAdapter
                mViewPager.setPageTransformer(false, mFragmentCardShadowTransformer)
                mViewPager.offscreenPageLimit = mFragmentCardAdapter!!.count
                if (markerList.isNotEmpty())
                {
                    selectMarkerPos = 0
                    moveTo(data.list[0])
                }
            }
        }
    }

    private fun initViewPageListener()
    {
        mViewPager.clearOnPageChangeListeners()
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener
                                           {
                                               override fun onPageScrollStateChanged(p0: Int)
                                               {
                                               }

                                               override fun onPageScrolled(p0: Int, p1: Float, p2: Int)
                                               {
                                               }

                                               override fun onPageSelected(p0: Int)
                                               {
                                                   try
                                                   {
                                                       markerList[selectMarkerPos].icon = markerIcon
                                                       markerList[p0].icon = markerIconBig
                                                       if (selectType != "ROUTE")
                                                       {
                                                           curLatLng = markerList[p0].position
                                                       }
                                                       selectMarkerPos = p0
                                                       val bundle = markerList[p0].extraInfo
                                                       val data: MainItemVo =
                                                               bundle.getSerializable("data") as MainItemVo
                                                       LogTool.ni("选中p0 = " + p0 + " -> " + data.proName)
                                                       moveTo(data)
                                                       // 判断到了最后一个
                                                       if (hasMore && p0 == cardSize - 1)
                                                       {
                                                           val body = BaseModel()
                                                           body.startLat = mCurrentLat.toString()
                                                           body.startLong = mCurrentLon.toString()
                                                           body.type = selectType
                                                           body.distance = Constant.STR_DISTANCE
                                                           body.page = page.toString()
                                                           mPresenter.getData(HttpDto(Constant.TYPE_LIST,
                                                                                      body).setType(
                                                                   HttpDto.GET))
                                                       }
                                                   }
                                                   catch (e: Exception)
                                                   {
                                                       e.printStackTrace()
                                                   }
                                               }
                                           })
    }

    public fun getCardData(pos: Int): MainItemVo
    {
        return fragmentDatas[pos]
    }

    // ============================== 目的地卡片 end ==============================
    // --------------- POP ---------------
    var popLayout: PopLayout? = null

    private fun showPop()
    {
        popLayout
                ?: let {
                    // 显示一个自定义View的pop
                    popLayout =
                            PopLayout(this@MainActivity,
                                      ViewGroup.LayoutParams.WRAP_CONTENT,
                                      ViewGroup.LayoutParams.WRAP_CONTENT,
                                      R.layout.view_pop_main)
                    popLayout?.contentView!!.findViewById<TextView>(R.id.vTvMain)
                            .setOnClickListener {
                                mScrollLayout.setToClosed()
                                mLLFoot.visibility = View.GONE
                                mLLTop.visibility = View.VISIBLE
                                popLayout?.dismiss()
                            }
                    popLayout?.contentView!!.findViewById<TextView>(R.id.vTvLine)
                            .setOnClickListener {
                                start(RouteMainActivity::class.java)
                                popLayout?.dismiss()
                            }
                    popLayout?.contentView!!.findViewById<TextView>(R.id.vTvProduct)
                            .setOnClickListener {
                                start(ProductListActivity::class.java)
                                popLayout?.dismiss()
                            }
                    popLayout?.contentView!!.findViewById<TextView>(R.id.vTvCommunity)
                            .setOnClickListener {
                                start(CommunityListActivity::class.java)
                                popLayout?.dismiss()
                            }
                    popLayout?.setOnDismissListener {
                        mIvMore.setImageResource(R.drawable.i_more)
                    }
                }
        popLayout?.show(mIvMore)
        mIvMore.setImageResource(R.drawable.i_more_yes)
    }

    // --------------- Token ---------------
    private fun checkToken()
    {
        if (RegTool.isNotEmpty(SpTool.getString(Constant.STR_TOKEN)))
        {
            if (Date().time - SpTool.getLong(Constant.LONG_TOKEN,
                                             Date().time) > 12 * 60 * 60 * 1000)
            {
                val body = BaseModel()
                body.oldToken = SpTool.getString(Constant.STR_TOKEN)
                mPresenter.getData(HttpDto(Constant.REFRESH_TOKEN, body, true).setShowError(false))
            }
        }
    }

    override fun refreshSuccess(data: LoginVo)
    {
        data.birthStringDay = Util.getTimeStr(data.birthDay)
        SpTool.saveString(Constant.STR_TOKEN, data.appToken)
        SpTool.saveLong(Constant.LONG_TOKEN, Date().time)
        SpTool.saveString(Constant.STR_MOBILE, data.mobile)
        SpTool.saveString(Constant.STR_USER_PHOTO, data.headImg)
        SpTool.saveString(Constant.STR_USER_NAME, DataTool.formatPhone(data.userName))
        SpTool.saveObject(Constant.OBJ_LOGIN, data)
    }

    // --------------- 搜索 ---------------
    private var keyword = ""

    private fun cleanSearch()
    {
        mIvSearchClear.visibility = View.GONE
        mTvSearch.text = ""
        keyword = ""
        mainTypeList()
    }
    
    @Subscribe
    fun onEvent(event: SearchEvent)
    {
        keyword = event.keyword
        mIvSearchClear.visibility = View.VISIBLE
        mTvSearch.text = keyword
        mScrollLayout.setToOpen()
        mLLFoot.visibility = View.VISIBLE
        mLLTop.visibility = View.GONE
        mTvToTop.visibility = View.GONE
        mRecyclerView.scrollToPosition(0)
        mainTypeList()
    }
}